package com.example.demoweb.controller;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.codec.binary.Hex;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

@RestController
public class Test {
	
	@RequestMapping("/test/tree")
	public void test() {
		try{
			String jsonStr="{\"header\":{\"terminal\":\"1\",\"deviceId\":\"867570021715507\",\"deviceDescription\":\"m2 note\",\"version\":\"1.9.2\",\"timestamp\":\"20170307163109\",\"uuid\":\"120170307163109000000324\"},\"body\":{\"optionId\":\"00\",\"cityId\":\"0532\",\"region\":\"370212\",\"netpoint\":\"\",\"userId\":\"operationuser\",\"tel\":\"18953280420\",\"transactionType\":\"3023\",\"transactionData\":{\"menuId\":\"Serv	iceManage\",\"formId\":\"AddService\",\"itemName\":\"洗浴服务\"}},\"sign\":\"hdfasfkjasdfkasdkfdkkjdjkg123424234534\"}";
			Gson gson = new Gson();
			//StreamData sd = gson.fromJson(jsonStr,StreamData.class);
			JsonObject streamDataJo = gson.fromJson(jsonStr,JsonObject.class);
			JsonObject headerJo = streamDataJo.get("header").getAsJsonObject();
			JsonObject bodyJo = streamDataJo.get("body").getAsJsonObject();
			JsonElement signJe = streamDataJo.get("sign");
			
			Set headerSet = headerJo.keySet();
			String headerStr = mySort(headerSet,headerJo);
			
			Set bodySet = bodyJo.keySet();
			String bodyStr = mySort(bodySet,bodyJo);
			
			String combineStr = headerSet + "," + bodyStr; 
			String encryptStr = encrypt(combineStr);
			
			System.out.println(combineStr);
			System.out.println(encryptStr);

	    } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	}
	
	public String mySort(Set set,JsonObject jo) {
		TreeSet<String> headerTreeSet = new TreeSet<String>();
		headerTreeSet.addAll(set);
		Iterator headerIt = headerTreeSet.iterator();
		StringBuffer sb = new StringBuffer();
		while(headerIt.hasNext()) {
			sb.append(jo.get(headerIt.next().toString())+",");
		}
		String resultStr = sb.substring(0, sb.length()-1);
		return resultStr;
	}
	
	public String encrypt(String str) throws UnsupportedEncodingException {
		String resultStr = "";
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] newStr=md5.digest(str.getBytes("utf-8"));
		    //加密后的字符串
			resultStr = Hex.encodeHexString(newStr);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return resultStr;
	}
}
